<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listHoliday, addHoliday, updateHoliday, delHoliday } from '../../api/holiday'
import { listUsertable } from '../../api/usertable'
import { listDepartment } from '../../api/department'

// 表格数据
const holidayList = ref([])
const userList = ref([])
const departmentList = ref([])
const loading = ref(false)
const total = ref(0)

// 查询参数
const queryParams = reactive({
  userId: undefined,
  departmentId: undefined,
  holidayDate: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  userId: undefined,
  holidayDate: undefined,
  reason: ''
})

const defaultForm = { id: undefined, userId: undefined, holidayDate: undefined, reason: '' }

// 弹窗控制
const open = ref(false)
const title = ref('')
const formRef = ref(null)

// 表单校验规则
const rules = {
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  holidayDate: [{ required: true, message: '请选择假期日期', trigger: 'change' }],
  reason: [{ required: true, message: '请输入请假原因', trigger: 'blur' }]
}

// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    const res = await listHoliday(queryParams)
    holidayList.value = res
    total.value = res.length
  } catch (error) {
    console.error('获取假期列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const getUserList = async () => {
  try {
    const res = await listUsertable()
    userList.value = res.filter(item => item.roleId === 3) // 只筛选医护人员
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 获取科室列表
const getDepartmentList = async () => {
  try {
    const res = await listDepartment()
    departmentList.value = res
  } catch (error) {
    console.error('获取科室列表失败:', error)
  }
}

// 表单重置
const reset = () => {
  formRef.value?.resetFields()
  Object.assign(form, defaultForm)
}

// 查询
const handleQuery = () => {
  getList()
}

// 重置
const resetQuery = () => {
  Object.keys(queryParams).forEach(key => {
    queryParams[key] = undefined
  })
  handleQuery()
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加假期'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const id = row.id || row.id
  Object.assign(form, row)
  open.value = true
  title.value = '修改假期'
}

// 提交按钮
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await updateHoliday(form)
          ElMessage.success('修改成功')
        } else {
          await addHoliday(form)
          ElMessage.success('新增成功')
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 删除按钮操作
const handleDelete = (row) => {
  const ids = row.id || row.id
  ElMessageBox.confirm('确认删除该假期记录吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await delHoliday(ids)
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 格式化日期
const formatDate = (row, column) => {
  if (!row.holidayDate) return ''
  const date = new Date(row.holidayDate)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取用户名称
const getUserName = (userId) => {
  const user = userList.value.find(item => item.id === userId)
  return user ? user.userName : ''
}

// 获取科室名称
const getDepartmentName = (userId) => {
  const user = userList.value.find(item => item.id === userId)
  if (!user) return ''
  
  const department = departmentList.value.find(item => item.id === user.departmentId)
  return department ? department.departmentName : ''
}

// 导出假期表
const exportHoliday = () => {
  if (holidayList.value.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }
  
  // 创建表格内容
  let content = '医护人员,科室,假期日期,请假原因\n'
  
  holidayList.value.forEach(item => {
    const userName = getUserName(item.userId)
    const departmentName = getDepartmentName(item.userId)
    const date = formatDate(item)
    
    content += `${userName},${departmentName},${date},${item.reason || ''}\n`
  })
  
  // 创建并下载文件
  const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  
  link.setAttribute('href', url)
  link.setAttribute('download', `假期表_${new Date().toISOString().split('T')[0]}.csv`)
  link.style.visibility = 'hidden'
  
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('导出成功')
}

// 页面加载时获取数据
onMounted(() => {
  getUserList()
  getDepartmentList()
  getList()
})
</script>

<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">假期管理</span>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="科室" prop="departmentId">
          <el-select v-model="queryParams.departmentId" placeholder="请选择科室" clearable>
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.departmentName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="医护人员" prop="userId">
          <el-select v-model="queryParams.userId" placeholder="请选择医护人员" clearable>
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.userName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="假期日期" prop="holidayDate">
          <el-date-picker
            v-model="queryParams.holidayDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区域 -->
      <el-row :gutter="10" class="mb-4">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="Download" @click="exportHoliday">导出假期表</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="holidayList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" align="center" label="序号" />
        <el-table-column prop="userId" label="医护人员" align="center" :formatter="(row) => getUserName(row.userId)" />
        <el-table-column prop="userId" label="所属科室" align="center" :formatter="(row) => getDepartmentName(row.userId)" />
        <el-table-column prop="holidayDate" label="假期日期" align="center" :formatter="formatDate" />
        <el-table-column prop="reason" label="请假原因" align="center" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/修改对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="医护人员" prop="userId">
            <el-select v-model="form.userId" placeholder="请选择医护人员">
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.userName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="假期日期" prop="holidayDate">
            <el-date-picker
              v-model="form.holidayDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="请假原因" prop="reason">
            <el-input v-model="form.reason" type="textarea" :rows="3" placeholder="请输入请假原因" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.mb-4 {
  margin-bottom: 16px;
}

.dialog-footer {
  text-align: right;
}
</style> 